import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect

from pacp.lib.base import BaseController, render
from pacp import model
from pylons.decorators import jsonify

log = logging.getLogger(__name__)

from pacp.model import run_flds

def get_record(r):
    result = {}
    flds = [x for x in dir(r) if not x.startswith('_')]
    for fld in flds:
        result[fld] = getattr(r, fld)
    return result

class RunController(BaseController):
    """REST Controller styled on the Atom Publishing Protocol"""
    # To properly map this controller, ensure your config/routing.py
    # file has a resource setup:
    #     map.resource('run', 'run')



    def search_run(self):
        # a sample of how to query using sql statement
        from pacp.model import meta
        defects =  meta.Session.query(Run).from_statement("select * from Runs where (select count(*) from details where ConditionCode='MGO' and  details.RunID=Runs.RunID) < 2").all().details
        results = []
        for defect in defects:
            result = {}
            for fld in detail_flds:
                result[fld] = getattr(defect, fld)
            results.append(result)
        return {'totalcount': len(defects), 'details': results}
    
    @jsonify
    def index(self, format='html' ):
        """GET /run: All items in the collection"""
        try:
            limit = int(request.params['limit'])
        except:
            limit = 25
        try:
            start = int(request.params['start'])
        except:
            start = 0
        try:
            query = request.params['query']
        except:        
            query = None
        if query:
            q_str = '%%%s%%' % query
            print q_str
            q = model.meta.Session.query(model.Run).filter(model.Run.PIPETECHID.like(q_str))
        else:
            q = model.meta.Session.query(model.Run)
       
        result = []
        for r in q[start:start +limit]:
            record = {}
            for fld in run_flds:
                record[fld] = getattr(r, fld)
            result.append(record)
        return {'totalcount': q.count(), 'runs': result}
        # url('run')

    def create(self):
        """POST /run: Create a new item"""
        # url('run')

    def new(self, format='html'):
        """GET /run/new: Form to create a new item"""
        # url('new_run')

    def update(self, id):
        """PUT /run/id: Update an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="PUT" />
        # Or using helpers:
        #    h.form(url('run', id=ID),
        #           method='put')
        # url('run', id=ID)

    def delete(self, id):
        """DELETE /run/id: Delete an existing item"""
        # Forms posted to this method should contain a hidden field:
        #    <input type="hidden" name="_method" value="DELETE" />
        # Or using helpers:
        #    h.form(url('run', id=ID),
        #           method='delete')
        # url('run', id=ID)
    @jsonify
    def show(self, id, format='json'):
        """GET /run/id: Show a specific item"""
        q = model.meta.Session.query(model.Run)
        r = q.get(int(id))
        result = {}
        
        for fld in run_flds:
            result[fld] = getattr(r, fld)

        

        return result
        
        
        # url('run', id=ID)

    def edit(self, id, format='html'):
        """GET /run/id/edit: Form to edit an existing item"""
        # url('edit_run', id=ID)
